var layer = layui.layer
var form = layui.form;
var laytpl = layui.laytpl;
var upload = layui.upload;
var $ = jQuery = layui.jquery;

function genderShow(type) {
    switch (type) {
        case "MALE":
            return "男";
        case "FEMALE":
            return "男";
        default:
            return "未知";
    }
}


//时间格式化
Date.prototype.format = function(fmt) { //author: meizz 
    var o = {
        "Y+": this.getFullYear(), //完整年份
        "y+": this.getFullYear() % 100, //年份后2位 
        "m+": this.getMonth() + 1, //月份 
        "M+": this.getMonth() + 1, //月份
        "D+": this.getDate(), //日 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "h+": this.getHours(), //小时  
        "I+": this.getMinutes(), //分 
        "i+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "S+": this.getMilliseconds(), //毫秒
    };
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (((k == "Y+" ? "0000" : "00") + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

//内容导引
var contentGuideApi = {
    getOne: function(type, success, error) {
        if (typeof success != "function") {
            return;
        }
        G.get('api/contentGuide/' + type, {}, function(data) {
            var list = JSON.parse(data.value);
            success(list);
        }, error)
    }
}

$(function() {
    var html = "";
    html += "<li class='nav-address'>四川省成都市锦江区一环路东5段东恒国际</li>";
    html += "<li class='nav-email'>sdk@sharestock.cn</li>";
    html += "<li class='nav-tel'>028-61533448</li>";
    $(".nav-contact .address").html(html);
    $('title').html('报告涨官-思多客')
})

//导航
$(function() {
    var menus = [
        { url: 'index.html', title: '首页', socpe: ['index.html'] },
        { url: "company.html", title: "企业介绍", socpe: ["company.html"] },
        { url: "video.html", title: "节目专栏", socpe: ["video.html"] },
        // { url: "payment.html", title: "研究报告", socpe: ["payment.html"] },
        // { url: "article.html", title: "主题研究", socpe: ["article.html"] },
        { url: "reward.html", title: "悬赏答疑", socpe: ["reward.html", "reward-detail.html"] },
        { url: "filter.html", title: "老师筛选", socpe: ["filter.html"] },
        { url: "contact.html", title: "联系我们", socpe: ["contact.html"] },
    ];

    var html = "";
    var pathname = location.pathname;
    var url = pathname.substr(pathname.lastIndexOf("/") + 1, pathname.length);
    for (var i = 0; i < menus.length; i++) {
        var menu = menus[i];
        var addClass = menu.socpe.indexOf(url) !== -1;

        html += "<li class='" + (addClass ? "current" : "") + "'><a href='" + menu.url + "'><span class='menu-title'>" + menu.title + "</span><span class='menu-bar'></span></a></li>";
    }
    $(".menu").html("<ul>" + html + "</ul>");
})

$(function(){
    var str = '<div class="reg-label" id="regLabel">\
        <span class="register">注册</span>/<span class="login">登录</span>\
    </div>\
    <div class="logined" id="logined"></a><span class="user-thumbs user-msg"><i class="user-icons"><img src="'+G.defaultAvator+'" alt="" data-lazyload-img="'+G.getCookie("sdk_user_avator")+'" class="avator" /></i></span>\
    <span>个人中心</span>\
    </div>'
    $('.tool-side').html(str);
    isLogined()
})

//判断是否登录
function isLogined() {
    G.getCookie('jwt') ? $('#logined').toggle() : $('#regLabel').toggle()
}

//页脚
$(function(){
    var str = '<div class="row">\
        <div class="tips inline-block">\
            <h5>风险提示</h5>\
            <p>1.本网站内容及各类报告文件内容，可能受著作权保护，网站开发公司与内容的出处无关，请在获得权利人合法授权后使用。<br>\
            2.本网站内容及各类报告文件内容，由相关法律许可从业人员就当前投资市场环境进行客观分析和研究，相关数据和标准均不作为买卖的依据，只作为买卖的参考；客户的各类投资获利及亏损与本网站及内容提供者均无法律关系。<br>\
            3.本网站内容均由相关法律许可从业人员提供，与本网站无关也不代表本网站观点，切格局《证券法及从业人员规定》，本网站有权对相关从业人员个人信息保密，在未征得权利人同意的情况下不得泄漏。<br>\
            4.投资有风险，入市需谨慎。</p>\
        </div>\
        <div class="cooperations inline-block">\
            <h5>合作机构</h5>\
            <ul>\
                <li><a href="http://www.youku.com"><img src="/public/images/sdk_yk.jpg" alt="优酷视频"></a></li>\
                <li><a href="http://www.cmbc.com.cn"><img src="/public/images/sdk_ms.jpg" alt="民生银行"></a></li>\
                <li><a href="https://www.alipay.com"><img src="/public/images/sdk_alipay.jpg" alt="支付宝"></a></li>\
                <li><a href="https://weixin.qq.com"><img src="/public/images/sdk_wx.jpg" alt="微信"></a></li>\
                <li><a href="http://www.miaopai.com/"><img src="/public/images/sdk_mp.jpg" alt="秒拍"></a></li>\
                <li><a href="https://v.qq.com"><img src="/public/images/sdk_tx.jpg" alt="腾讯视频"></a></li>\
            </ul>\
        </div>\
        <div class="certificate inline-block">\
            <h5>相关证书</h5>\
            <ul>\
                <li><img src="/public/images/sdk_c1.jpg" alt=""></li>\
                <li><img src="/public/images/sdk_c2.jpg" alt=""></li>\
                <li><img src="/public/images/sdk_c3.jpg" alt=""></li>\
                <li><img src="/public/images/sdk_c4.jpg" alt=""></li>\
                <li><img src="/public/images/sdk_c5.jpg" alt=""></li>\
                <li><img src="/public/images/sdk_c6.jpg" alt=""></li>\
            </ul>\
        </div>\
    </div>\
    <div class="tac size12"><a href="http://www.miitbeian.gov.cn/">蜀ICP备17029708号-1</a> &copy; 成都思多客网络科技有限公司版权所有</div>'
    $('.footer').html(str)
})

/*导航切换*/
$(document).on("mouseover", ".menu li", function() {
    $(this).addClass('S_current');
}).on("mouseout", ".menu li", function() {
    $(this).removeClass('S_current');
})


/*注册*/
$(document).on('click', '.register, #openRegisterLayer, #goPre', function() {
    registerModel()
})

//注册弹窗模板
function registerTpl() {
    var str = '<div class="register-layer" id="regLayer">\
        <div class="register-header">\
            <div class="vip-customer current-type">投资者注册</div>\
            <div class="common-customer" id="J_common_reg">分析师注册</div>\
        </div>\
        <div class="register-body">\
            <div class="invite-code">请输入您的邀请码：\
                <input type="text" id="J_invite_code">\
            </div>\
            <div class="phone-reg-btn" id="openPhoneRegLayer">下一步</div>\
            <div class="go-login">已有账号，去<span class="open-login-layer" id="openLoginLayer">登录</span></div>\
        </div>\
    </div>'
    return str;
}

//登录弹窗模板
function loginTpl(){
    var str = '<div class="login-layer" id="loginLayer">\
        <div class="login-header">登录</div>\
        <div class="login-body">\
            <div class="username-content">\
                <div class="username">\
                    <input class="user-input" type="text" placeholder="手机号码" id="logUser"><span class="validate" id="validateLogName"></span>\
                </div>\
                <div class="login-tips" id="J_login_user_tip"></div>\
            </div>\
            <div class="password-content">\
                <div class="password">\
                    <input class="pwd-input" type="password" placeholder="密码" id="logPwd"><span class="validate" id="validateLogPwd"></span>\
                </div>\
                <div class="login-tips" id="J_login_pwd_tip"></div>\
            </div>\
            <div class="login-btn" id="J_loginBtn">登录</div>\
            <div class="login-check-bar">\
                <div class="fl">\
                    <input type="checkbox" id="autoLogin">\
                    <label for="autoLogin">下次自动登录</label>\
                </div>\
                <div class="fr">没有账号？去<span class="open-login-layer" id="openRegisterLayer">注册</span></div>\
            </div>\
            <div class="other-login">\
                <h4>第三方账号登录</h4>\
                <ul>\
                    <li><a class="other-entry J_oauth_button qq" data-type="qq" href="javascript:void(0);"></a></li>\
                    <li><a class="other-entry J_oauth_button wechat" data-type="wx" href="javascript:void(0);"></a></li>\
                    <li><a class="other-entry J_oauth_button alipay" data-type="alipay" href="javascript:void(0);"></a></li>\
                </ul>\
            </div>\
        </div>\
    </div>';
    return str;
}

//分析师注册弹窗模板
function vipRegTpl(inviteCode){
    var str = '<div class="reg-contain" id="phoneRegLayer">\
        <div class="phone-header">\
            <div class="pre-step" id="goPre">&lt; 上一步</div>\
            <div class="phone-title" id="J_reg_title"></div>\
        </div>\
        <div class="phone-body">\
            <div class="username-content">\
                <div class="username">\
                    <input class="user-input" type="text" placeholder="手机号码" id="regUser"><span class="validate" id="validateName"></span>\
                </div>\
                <div class="login-tips" id="J_reg_user_tip"></div>\
            </div>\
            <div class="password-content">\
                <div class="password">\
                    <input class="pwd-input" type="password" placeholder="密码" id="regPwd"><span class="validate" id="validatePwd"></span>\
                </div>\
                <div class="login-tips" id="J_reg_pwd_tip"></div>\
            </div>\
            <div class="login-btn" id="J_reg_btn" data-code="'+(inviteCode ? inviteCode : "")+'">注册</div>\
            <div class="login-check-bar">\
                <div class="fr">已有账号，去<span class="open-login-layer" id="goLoginLayer">登录</span></div>\
            </div>\
            <div class="other-login">\
                <h4>第三方账号注册</h4>\
                <ul>\
                     <li><a class="other-entry J_oauth_button qq" data-type="qq" href="javascript:void(0);"></a></li>\
                    <li><a class="other-entry J_oauth_button wechat" data-type="wx" href="javascript:void(0);"></a></li>\
                    <li><a class="other-entry J_oauth_button alipay" data-type="alipay" href="javascript:void(0);"></a></li>\
                </ul>\
            </div>\
        </div>\
    </div>'
    return str;
}

function registerModel() {
    layer.closeAll();
    $('#J_invite_code').val('')
    layer.open({
        area: ['800px', '550px'],
        title: false,
        closeBtn: 0,
        shadeClose: true,
        type: 1,
        scrollbar: false,
        content: registerTpl()
    });
}

function loginModel() {
    layer.closeAll();
    layer.open({
        area: ['500px', 'auto'],
        title: false,
        closeBtn: 0,
        shadeClose: true,
        type: 1,
        scrollbar: false,
        content: loginTpl()
    });
}
//已有账号,登录
$(document).on('click', '.login, #openLoginLayer, #goLoginLayer', function() {
    loginModel()
})

//免费下载提示登录
$(document).on('click','.down-free',function(){
	var productId = $(this).data('id');
    if(!G.getCookie('jwt')){
        loginModel()        
    }else{
    	user.getInfo({},function(){
	        paySuccess(G.apiurl + 'api/product/'+productId+'/download?token='+G.getCookie('jwt'))
    	})
    }
})

function vipRegistModel(title,inviteCode) {
    layer.closeAll();
    reset();
    layer.open({
        area: ['800px', 'auto'],
        title: false,
        closeBtn: 0,
        shadeClose: true,
        type: 1,
        scrollbar: false,
        content: vipRegTpl(inviteCode)
    });
    $('#J_reg_title').html(title)
}

//预约老师
$(function(){
    var str = '<div class="row">\
            <img src="public/images/sdk_yu.png" alt="">\
            <div class="describe">\
                <div class="appointment-teacher"><img class="coverUrl" src="public/images/sdk_wx_qrcode.jpg" alt="思多客客服"></div>\
                <div class="appointment-describe">个人对老师有特别服务需要，请扫二维码加老师助理客服，陈述需求，我们会安排3个工作日安排老师与您进行电话沟通，预约老师每次收费10元。</div>\
            </div>\
        </div>'
    $('.appointment').html(str)
})


//支付弹窗模板
function createPayTpl(user,product){
    console.log(user,product)
    var productType = product.type.slice(0,1);
    var isVip;
    switch(productType){
        case 'A':
            if(user.vipDayA > 0){
                isVip = true;
            }
            break;
        case 'B':
            if(user.vipDayB > 0){
                isVip = true;
            }
            break;
        default:
            isVip = false;
            return;
    }
    var str = '<div class="reward-layer" id="rewardLayer">'+
        '<div class="teacherInfo-layer-head">赏金支付</div>'+
            '<div class="pay-layer-body" id="J_pay_body">'+
               ' <div class="recharge-user-info">'+
                    '<div class="user-info-contain inline-block">'+
                        '<div class="user-info-item" id="J_reward_userInfo">'+
                            '<div class="rewarder-icon fl"><img src="'+G.defaultAvator+'" data-lazyload-img="'+G.uploadurl+'/avator/'+user.userId+'.png" class="avator">'+
                            '</div>'+
                            '<div class="user-name fl">用户名: <span class="name">'+formatVal(user.username)+'</span></div>'+
                            '<div class="user-money-remain fr">剩余金币: <span class="money">'+user.balance+'</span></div>'+
                        '</div>'+
                    '</div>'+
                '</div>'+
                '<div class="reward-info">'+
                    '<div class="reward-product">'+
                        '<div class="product-info">'+
                             '<div class="report-time">'+new Date(product.createTime).format('YYYYMMDD')+'</div>'+
                            '<div class="teacher-portrait"><img src="'+G.defaultAvator+'" data-lazyload-img="'+G.uploadurl+'/avator/'+product.teacherId+'.png" class="avator"></div>'+
                            '<p class="teacher-name">'+formatVal(product.aliasName)+'</p>'+
                            '<p class="outline">研究板块:<br>'+formatOutline(formatVal(product.outline))+'</p>'+
                        '</div>'+
                        '<div class="price-num">'+
                           '<b>'+formatVal(product.promotionsPrice,product.unitPrice)+'</b>赏币<br>'+
                           '或<br>'+
                           '<b>'+formatVal(product.promotionsPrice,product.unitPrice)+'</b>元<br>'+
                           // '<input type="button" value="预览" class="preview">'+
                        '</div>'+
                    '</div>';
            if(isVip){
                     str += '<div class="payType hide">'+
                                '<h3>支付方式:</h3>'+
                                '<div class="layui-form" lay-filter="reward-radio">'+
                                    '<div>'+
                                        '<input lay-filter="reward-radio" type="radio" name="payType" value="赏币支付" title="赏币支付" '+ ((user.balance - (product.promotionsPrice?product.promotionsPrice:product.unitPrice) < 0) ? "disabled": "checked" )+'><span class="balance-not-enough '+ ((user.balance - (product.promotionsPrice?product.promotionsPrice:product.unitPrice) < 0) ? "inline-block": "hide" )+'">余额不足,还需支付'+(((product.promotionsPrice?product.promotionsPrice:product.unitPrice) - user.balance)+'').substring(0,5)+'元,请选择下列方式支付</span>'+  
                                    '</div>'+
                                    '<div>'+
                                       '<input lay-filter="reward-radio" type="radio" name="payType" value="网上支付" title="网上支付" '+ ((user.balance - (product.promotionsPrice?product.promotionsPrice:product.unitPrice) < 0) ? "checked": "" )+'>'+
                                   '</div>'+
                                '</div>'+
                                '<div class="clearfix">'+
                                    '<ul class="public-payment-list '+((user.balance - (product.promotionsPrice?product.promotionsPrice:product.unitPrice) < 0)? "show" : "hide") +'">'+
                                        '<li class="payment-item payment-alipay current-payment" data-type="alipay"></li>'+
                                        '<li class="payment-item payment-weixin" data-type="wx"></li>'+
                                        '<li class="payment-item payment-union" data-type="union"></li>'+
                                    '</ul>'+
                                    '<div class="fl"><img src="public/images/sdk_wx_pay.png" alt="" /></div>'+
                                    '<input type="hidden" id="J_oweMoney">'+
                                '</div>'+
                            '</div>'+
                        '</div>'+
                        '<div class="submit-reward" id="J_submit_reward">'+
                            '<input type="button" class="submit-reward-btn down-free" value="VIP下载" data-id="'+product.productId+'">'+
                        '</div>'+
                    '</div>'+
                '</div>'
            }else{
                 str += '<div class="payType">'+
                            '<h3>支付方式:</h3>'+
                            '<div class="layui-form" lay-filter="reward-radio">'+
                                '<div>'+
                                    '<input lay-filter="reward-radio" type="radio" name="payType" value="赏币支付" title="赏币支付" '+ ((user.balance - (product.promotionsPrice?product.promotionsPrice:product.unitPrice) < 0) ? "disabled": "checked" )+'><span class="balance-not-enough '+ ((user.balance - (product.promotionsPrice?product.promotionsPrice:product.unitPrice) < 0) ? "inline-block": "hide" )+'">余额不足,还需支付'+(((product.promotionsPrice?product.promotionsPrice:product.unitPrice) - user.balance)+'').substring(0,5)+'元,请选择下列方式支付</span>'+  
                                '</div>'+
                                '<div>'+
                                   '<input lay-filter="reward-radio" type="radio" name="payType" value="网上支付" title="网上支付" '+ ((user.balance - (product.promotionsPrice?product.promotionsPrice:product.unitPrice) < 0) ? "checked": "" )+'>'+
                               '</div>'+
                            '</div>'+
                            '<div class="clearfix">'+
                                '<ul class="public-payment-list '+((user.balance - (product.promotionsPrice?product.promotionsPrice:product.unitPrice) < 0)? "show" : "hide") +'">'+
                                    '<li class="payment-item payment-alipay current-payment" data-type="alipay"></li>'+
                                    '<li class="payment-item payment-weixin" data-type="wx"></li>'+
                                    '<li class="payment-item payment-union" data-type="union"></li>'+
                                '</ul>'+
                                '<div class="fl"><img src="public/images/sdk_wx_pay.png" alt="" /></div>'+
                                '<input type="hidden" id="J_oweMoney">'+
                            '</div>'+
                        '</div>'+
                    '</div>'+
                    '<div class="submit-reward" id="J_submit_reward">'+
                        '<input type="button" id="layerPayBtn" class="submit-reward-btn" value="立即支付" data-id="'+product.productId+'" data-price="'+(product.promotionsPrice?product.promotionsPrice:product.unitPrice)+'" data-balance="'+user.balance+'">'+
                    '</div>'+
                '</div>'+
            '</div>'
            }
        return str;
}


//打赏，支付弹窗
function openPayLayer(productId, cancelMsg) {
    //点击下载，付费，悬赏 如果没有cookie就弹出登录
    if(!G.getCookie('jwt')){
        loginModel();
        return
    }
    layer.load(1)
    product.findOne(productId,{},function(productInfo){
        user.getInfo({}, function(user) {
            var dom = createPayTpl(user,productInfo)
            lazyload()
            layer.closeAll();
            layer.open({
                area: ['800px', '580px'],
                title: false,
                closeBtn: 2,
                type: 1,
                scrollbar: false,
                content: dom,
                cancel: function() {
                    layer.msg(cancelMsg)
                }
            })
            form.render('radio','reward-radio')
            lazyload()
        })
    },function(){
        layer.closeAll();
        layer.msg('系统繁忙，请稍后再试')
    })
}


form.on('radio(reward-radio)',function(data){
    var btn = $('#layerPayBtn');
    var price = btn.data('price')
    var balance = btn.data('balance')
    var payMoney = balance - price;
    if(payMoney >= 0){
        $('.public-payment-list').toggle()
    }
})

// 弹窗支付
$(document).on('click','#layerPayBtn',function(){
    var price = $(this).data('price');
    var productId = $(this).data('id');
    var balance = $(this).data('balance');
    var payType = $('.payment-item.current-payment').data('type');
    var radioVal = $('input[lay-filter="reward-radio"]:checked').val();
    var payMoney = balance - price;
    var params = {
        productId: productId,
        balancePay: price
    }
    if(payMoney >= 0){
        if(radioVal === '赏币支付'){
            cashPay(productId,params)
        }else{
            onlinePay(price,payType,productId,params)
        }
    }else{
        onlinePay(payMoney,payType,productId,params)
    }
})

function cashPay(productId,params){
    productOrder.add(productId,params,function(data){
        console.log(data)
        product.findOne(data.productId,{},function(product){
            console.log(product)
            if(product.payed){
                paySuccess(G.apiurl + 'api/product/'+productId+'/download?token='+G.getCookie('jwt'));
            }
        })
    })
}
function onlinePay(payMoney,payType,productId,params){
    if(payType === 'alipay'){
        var newOpen = window.open();        
    }
    rechargeApi.create(Math.abs(payMoney),{},function(data) {
        console.log(data)
        var orderId = data.rechargeOrderId;
        if(payType === 'wx'){
            G.get("pay/wx/rechargeOrder/web/" + orderId,{},function(data){
                layer.confirm('支付是否完成？', {title:false,closeBtn:false,btnAlign: 'c',btn:['完成支付','放弃支付']}, function(index){
                    rechargeOrder.getStatus(orderId,'wx',{},function(order){
                        cashPay(productId,params)
                    },function(e){
                        layer.msg('支付失败')
                    })
                },function(){
                    layer.msg('放弃支付')
                });
                wxPayTpl()
                $('#qrcode').qrcode(data.codeUrl);
                layer.open({
                    area: ['300px', 'auto'],
                    title: false,
                    closeBtn: 1,
                    type: 1,
                    shadeClose: false,
                    scrollbar: false,
                    content: $('#J_wx_tpl')
                })
            })
        }
        if(payType === 'alipay'){
            newOpen.location = rechargeOrder.getUrl(payType,data.rechargeOrderId,'web');
            layer.confirm('支付是否完成？', {title:false,closeBtn:false,btnAlign: 'c',btn:['完成支付','放弃支付']}, function(index){
                rechargeOrder.getStatus(orderId,'alipay',{},function(order){
                    cashPay(productId,params)
                },function(e){
                    layer.msg('支付失败')
                })
            },function(){
                layer.msg('放弃支付')
            });
        }
    })
}

function downloadProduct(url){
    setTimeout(function(){
        var a = $('<a href="" download="download"></a>');
        a.attr('href',url);
        a[0].click()
    },1000)
}

function downloadTpl(url){
    var str = '<div class="success-layer" id="successLayer">\
        <div class="success-layer-head">下载报告</div>\
        <div class="success-layer-body">\
            <h3 class="success-status">付费成功！</h3>\
            <img src="public/images/sdk_pay_success.jpg" alt="">\
            <p class="success-tips">已成功为您启动下载，\
                <br>若下载未启动或您的浏览器不支持自动下载，请点击<a href="'+url+'" class="success-download" download="download">手动下载</a></p>\
        </div>\
    </div>';
    return str;
}

function paySuccess(url){
    layer.closeAll();
    layer.open({
        area: ['800px', 'auto'],
        title: false,
        closeBtn: 2,
        type: 1,
        scrollbar: false,
        content: downloadTpl(url)
        
    })
    downloadProduct(url)
}

//图片懒加载
$((function(undefined){
    var lazyload = function(){
        var imgObjs = $("img[data-lazyload-img]");
        var el = [];
        var url = [];
        for (var i = 0; i < imgObjs.length; i++) {
            url[i] = $(imgObjs[i]).attr("data-lazyload-img");
            if (typeof url[i] == "string" && url[i].length > 0) {
                el[i] = new Image();
                el[i].setAttribute("data-id", i);
                el[i].onload = function() {
                    var i = $(this).attr("data-id");
                    var obj = $(imgObjs[i]);
                    obj.attr("src", obj.attr("data-lazyload-img")).removeAttr("data-lazyload-img");
                    el[i] = null;
                    url[i] = null;
                };
                el[i].onerror = function(){};
                el[i].src = url[i];
            }
        }
    };
    window.lazyload = lazyload;
})());


function reset() {
    //重置输入框及滑动
    $('#regUser').val('');
    $('#logUser').val('');
    $('#regPwd').val('');
    $('#logPwd').val('');
    $('#regUser').removeClass('validate-false');
    $('#validatePwd').removeClass('validate-false');
    $('#validateLogName').removeClass('validate-false');
    $('#validateLogPwd').removeClass('validate-false');
    $("#code-box span").css('left', '0');
    $("#code-box p").css('width', '0');
    $('#J_login_pwd_tip').html('');
    $('#J_reg_user_tip').html('');
}
$(document).on('click', '#openPhoneRegLayer', function() {
    var inviteCode = $('#J_invite_code').val();
    vipRegistModel('投资者注册',inviteCode)
})
$(document).on('click', '#J_common_reg', function() {
    vipRegistModel('分析师注册');
})


/*注册*/
$(document).on('click', '#J_reg_btn', function() {
    console.log('注册')
    var username = $('#regUser').val();
    var password = $('#regPwd').val();
    var code = $(this).data('code');
    if(!username){
        layer.msg('用户名不能为空')
        return;
    }
    if(!password){
        layer.msg('密码不能为空')
        return;
    }
    console.log('验证成功')
    var params = {
        username: username,
        secretkey: password,
        inviteCode: code
    }
    user.register(params, function(data) {
        $('#J_reg_user_tip').html('')
        layer.msg('注册成功,登录中...')
        // setTimeout(function(){
        //     location.reload();            
        // },1500)
        user.login(params, function(data) {
            if(data){
                var time = 60 * 24 * 1;
                G.setCookie('jwt', data.jwt, time)
                G.setCookie('sdk_user_id', data.user.userId, time)
                G.setCookie('sdk_user_type', data.user.userType, time)
                G.setCookie('sdk_user_avator', data.user.avatorUrl, time)
                setTimeout(function() {
                    layer.msg('登录成功')
                    location.reload();
                }, 1500)

            }
        }, function(err) {
            console.error(err)
            layer.msg(err)
            reset();
        })
    }, function(err) {
        console.error(err)
        layer.msg(err)
        reset();
    })
})

var registLayerTipsIndex;
function registLayerTips(){
    registLayerTipsIndex = layer.open({
        area: ['420px', '560px'],
        title: false,
        closeBtn: 0,
        type: 1,
        scrollbar: false,
        content: '<div class="bgzg-content" id="bgzg">\
                <p class="bgzg-logo"><img src="/public/images/logo.png" alt=""></p>\
                <p class="bgzg-title">扫码关注“报告涨官”<br>券商、机构、投顾等行业顶尖老师<br><span>\提供一对一诊股！</span></p>\
                <p class="bgzg-qrcode"><img src="/public/images/baogaozhangguan.jpg" alt=""></p>\
                <p class="bgzg-tips">关注后发送股票名称及代码即可~<br>每天还有新鲜投资干货推送！</p>\
                <button class="bgzg-focus-btn bgzg-focus-disabled" id="focus">关闭(5)</button>\
            </div>'
    })
    var i = 5;
    var interval = setInterval(function(){
        i--;
        $('#focus').html('关闭('+i+')')
        if(i == 0){
            clearInterval(interval)
            $('#focus').html('已关注')
            $('#focus').removeClass('bgzg-focus-disabled')
        }
    },1000)
}

$(document).on('click','#focus',function(){
    if($(this).hasClass('bgzg-focus-disabled')){
        return;
    }
    layer.close(registLayerTipsIndex)
    location.reload();
    // console.log(registLayerTipsIndex)
})
/*登录*/
$(document).on('click', '#J_loginBtn', function() {
    console.log('login-layer')
    var username = $('#logUser').val();
    var password = $('#logPwd').val();
    var rememberPwd = $('#autoLogin').is(":checked");
    console.log(username, password)
    if (username && password) {
        var params = {
            username: username,
            secretkey: password,
            remember: rememberPwd
        }
        user.login(params, function(data) {
            if(data){
                var time = rememberPwd ? 60 * 24 * 7 : 60 * 24 * 1;
                G.setCookie('jwt', data.jwt, time)
                G.setCookie('sdk_user_id', data.user.userId, time)
                G.setCookie('sdk_user_type', data.user.userType, time)
                G.setCookie('sdk_user_avator', data.user.avatorUrl, time)
                layer.msg('登录成功')
                registLayerTips()
                // setTimeout(function() {
                //     location.reload();
                // }, 1500)
            }
        }, function(err) {
            console.error(err)
            layer.msg(err)
            reset();
        })
    }
})


$(document).on('click', '#logined', function() {
    if (G.getCookie('jwt')) {
        if (G.getCookie('sdk_user_type') === 'TEACHER') {
            location.href = "teacher.html";
        } else {
            location.href = "user.html";
        }
    } else {
        loginModel();
    }
})

//退出登录
function userLogout() {
    G.deleteCookie('jwt');
    G.deleteCookie('sdk_user_id');
    G.deleteCookie('sdk_user_type');
    G.deleteCookie('rewardId');
    G.deleteCookie('localUserId');
    setTimeout(function() {
        location.href = "index.html"
    }, 2000)
}
function formatOutline(outline){
    return outline.replace(/\n/g,'<br>')
}

function formatVal(obj, defaultVal) {
    return obj ? obj : (defaultVal != undefined ? defaultVal : "-");
}


//退出登录
$(document).on('click','#J_logout',function(){
    layer.confirm('退出登录?', {icon: 3, title:'提示',yes:function(){
        layer.msg('退出成功!');
        userLogout();
    }});
})

$(document).on("click", ".J_oauth_button", function(){
    if ($(this).hasClass("disabled")) {
        layer.msg("暂未开通");
        return;
    }
    var type = $(this).attr("data-type");
    layer.load(1)
    var url = G.apiurl + "oauth2/" + type + "/authorize.do";
    location.href = url;
})

//修改密码
function updatePwdTpl(){
    var str = '<div class="update-pwd layui-form" id="upadtePwd">\
            <div class="layui-form-item">\
                <h4 class="update-title">修改密码</h4>\
            </div>\
            <div class="layui-form-item">\
                <label for="oldPwd" class="layui-form-label">旧密码</label>\
                <div class="layui-input-block">\
                  <input id="oldPwd" type="text" name="title" required  lay-verify="required" placeholder="请输入旧密码" autocomplete="off" class="layui-input">\
                </div>\
            </div>\
            <div class="layui-form-item">\
                <label for="newPwd" class="layui-form-label">新密码</label>\
                <div class="layui-input-block">\
                  <input id="newPwd" type="text" name="title" required  lay-verify="required" placeholder="请输入新密码" autocomplete="off" class="layui-input">\
                </div>\
            </div>\
            <div class="layui-form-item tac">\
                <input type="reset" value="取消" class="layui-btn layui-btn-primary layui-btn-small" id="handleCancel">\
                <input type="button" value="确定" class="layui-btn layui-btn-normal layui-btn-small" id="handelUpdatePwd">\
            </div>\
        </div>'
    return str;
}
$(document).on('click','#J_update_pwd',function(){
    layer.open({
        area: 'auto',
        title: false,
        closeBtn: 2,
        shadeClose: true,
        type: 1,
        scrollbar: false,
        content: updatePwdTpl()
    })
})
$(document).on('click','#handelUpdatePwd',function(){
    var oldSecretkey = $('#oldPwd').val();
    var newSecretkey = $('#newPwd').val();
    if(!oldSecretkey){
        layer.msg('请输入旧密码');
        return;
    }
    if(!newSecretkey){
        layer.msg('请输入新密码');
        return;
    }
    var params = {
        oldSecretkey: oldSecretkey,
        newSecretkey: newSecretkey
    }
    user.modifyPwd(params,function(){
        layer.msg('密码修改成功，请重新登录!');
        setTimeout(function(){
            G.deleteCookie('jwt');
            G.deleteCookie('sdk_user_id');
            G.deleteCookie('sdk_user_type');
            G.deleteCookie('rewardId');
            G.deleteCookie('localUserId');
            location.reload()
        },1500)

    })
})
$(document).on('click','#handleCancel',function(){
    layer.closeAll();
})

function wxPayTpl(){
    $('#J_wx_tpl').remove()
    var str = '<div class="wx-pay hide" id="J_wx_tpl">\
    <h3>扫描二维码进行支付</h3>\
    <div class="qrcode" id="qrcode"></div>\
    </div>';
    $('body').append(str);
}

$(document).on('click','.payment-item',function(){
    var type = $(this).data('type')
    if(type === 'union'){
        return
    }
    $(this).siblings('.payment-item').removeClass('current-payment');
    $(this).addClass('current-payment');
})